package com.xy6.dpdemo.book.chapter21.singleton;

/**
 * 单例类2
 * <p>获取实例时，加锁。
 * <p>缺点：并发环境下，每次获取实例都要加锁，性能差。
 * 
 * @author zhang
 * @since 2017-06-30
 */
public class Singleton2 {

	private static Singleton2 instance = null;
	
	private static Long time = 0L;
	
	/**
	 * 初始化
	 * <p>加睡眠，模拟初始化耗时很久
	 */
	private Singleton2(){
		System.out.println("begin init...");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		time++;
		System.out.println("end init..." + time);
	}
	
	public static synchronized Singleton2 getInstance(){
		if(null == instance){
			instance = new Singleton2();
		}
		return instance;
	}
	
	public void show(){
		System.out.println(time);
	}
	
}
